<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '','v-conter']"
              v-for="(item1 ,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close='removeRightById(scope.row,item1.id)' closable>{{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' :'bdtop', 'v-conter']"
                  v-for="(item2 ,i2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag @close='removeRightById(scope.row,item2.id)' closable type="success">
                      {{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag @close='removeRightById(scope.row,item3.id)' closable type="warning"
                      v-for="(item3,i3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column width="300" label="操作">
          <template slot-scope="scope">
            <div>
              <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)"
                icon="el-icon-edit">编辑</el-button>
              <el-button size="mini" @click="removeUser(scope.row.id)" type="danger"
                icon="el-icon-delete">删除</el-button>
              <el-button size="mini" @click="showSetRightDiaolog(scope.row)" type="warning"
                icon="el-icon-setting">分配权限</el-button>
            </div>
          </template>
        </el-table-column>

      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog @close="resetAddForm" title="提示" :visible.sync="addDialogVisible" label-width="70%">

      <!-- 内容主体区域 -->
      <el-form label-width="100px" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户区域 -->

    <el-dialog @close="resetEdit" title="修改角色" :visible.sync="editDialogVisible" label-width="70%">

      <!-- 内容主体区域 -->
      <el-form label-width="100px" :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog @close="closeSetRight" title="分配权限" :visible.sync="SetRightDiaologVisible"
      width="50%">
      <!-- 树形数据 -->
      <el-tree ref="treeRef" :default-checked-keys="defKeys" node-key='id' default-expand-all
        :data="rightsList" show-checkbox :props="treeProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDiaologVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      // 控制添加用户的对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户信息对话框的显示与隐藏
      editDialogVisible: false,
      // 控制权限分配的对话框的显示与隐藏
      SetRightDiaologVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      rightsList: [],
      //树形结构的数据绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      RoleId: ''
    }
  },
  created () {
    this.getRoutesList()
  },
  methods: {
    async getRoutesList () {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.rolesList = res.data;
    },
    addDialog () {

      this.addDialogVisible = true
    },
    // 表单重置操作
    resetAddForm () {
      console.log(2);

      this.$refs.addFormRef.resetFields();
    },
    resetEdit () {
      this.$refs.editFormRef.resetFields();
    },
    // 底部按钮 确定
    addrole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')

        this.$message.success('添加角色成功')
        this.addDialogVisible = false
        this.getRoutesList();
      })
    },
    // 根据id 获取对应的数据
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get("roles/" + id)
      if (res.meta.status !== 200) return
      this.editForm = res.data



    },
    // // 编辑弹出的对话框 底部按钮 确定 修改信息的事件
    editDialog () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getRoutesList()
      })
    },
    // 点击删除按钮 删除角色信息
    async removeUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认删除 confirmResult 返回confirm  取消删除返回 cancel
      if (confirmResult === 'cancel') {
        return this.$message.info('已取消删除操作')
      }

      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.getRoutesList();
      this.$message.success('已成功删除该角色信息')

    },
    async removeRightById (role, rightId) {
      const confir = await this.$confirm('此操作将永久删除该角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confir === 'cancel') {
        return this.$message.info('已取消删除操作')
      }

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除该角色权限失败')

      // this.getRoutesList();
      role.children = res.data
      this.$message.success('删除该角色权限成功')
    },
    async showSetRightDiaolog (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')

      this.rightsList = res.data
      this.RoleId = role.id
      this.getLeafKeys(role, this.defKeys)
      this.SetRightDiaologVisible = true

    },
    // 通过递归的形式，获取角色下所有三级权限的id ， 并保存到defKeys数组中
    getLeafKeys (node, arr) {
      // 如果当前node 节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    closeSetRight () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ... this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const IdStr = keys.join(',')
      console.log(IdStr);

      const { data: res } = await this.$http.post(`roles/${this.RoleId}/rights`, { rids: IdStr })
      if (res.meta.status !== 200) return
      this.$message.success('分配权限成功')
      this.getRoutesList()
      this.SetRightDiaologVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.v-conter {
  display: flex;
  align-items: center;
}
</style>